package com.shilun.demo.demo.swagger.execption;

import com.shilun.demo.demo.swagger.vo.ResultVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author sl shilun217@qq.com
 * @Deacription
 * @date 2021/12/04/23:36
 **/
@ControllerAdvice(annotations = Controller.class)
@Log4j2
public class GlobalExceptionResolver {
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultVo exceptionHandler(Throwable e) {
        return ResultVo.failureMsg("出错了:" + e.getMessage());
    }

    /**
     * 参数必填校验的捕获
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVo MyExceptionHandle(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder sb = new StringBuilder();
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                sb.append(error.getDefaultMessage());
            }
        }
        String message = sb.toString();
        return ResultVo.failureMsg(message);
    }
}
